package com.luxsoft.siipap.em.replica.importadores.cxc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.luxsoft.siipap.em.replica.importadores.ImportacionCanceledException;
import com.luxsoft.siipap.model.Periodo;
import com.luxsoft.siipap.model.core.Cliente;
import com.luxsoft.siipap.model.core.ClienteCredito;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.service.core.ClienteManager;
import com.luxsoft.siipap.util.DBUtils;

/**
 * Importa y/o actualiza el catalogo de clientes de SIIPAP a SiipapEx
 *   
 * @author Ruben Cancino
 *
 */
public class ImportadorDeClientes {
	
	public static final String SQL="SELECT * FROM CLIENTES_TO_MYSQL2 WHERE FRECUENTE=1  order by CLAVE desc";
	
	protected static Logger logger=Logger.getLogger(ImportadorDeClientes.class);
	private RowMapper clienteMapper=new ClienteMapper();
	
	public Cliente importar(String clave){
		String sql="SELECT * FROM CLIENTES_TO_MYSQL2 WHERE CLAVE=?";
		List<Cliente> cc = getSourceTemplate().query(sql, new String[]{clave},clienteMapper);
		if(cc.isEmpty()) return null;
		Cliente source=cc.get(0);
		Cliente target=getClienteManager().buscarPorClave(source.getClave().trim());
		if(target!=null){
			return actualizarCliente(target, source);			
		}
		return getClienteManager().save(source);
		
	}
	
	/**
	 * Migra los clientes de Oracle a MySQL
	 * 
	 *  
	 * @param p
	 */
	public void importar(final Periodo p){
		
		getSourceTemplate().query(SQL,new ResultSetExtractor(){
			public Object extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				while(rs.next()){
					try {
						Cliente source=procesar(rs);
						Cliente target=getClienteManager().buscarPorClave(source.getClave());
						if(target==null){
							target=importarClienteNuevo(source);
						}else{
							actualizarCliente(target,source);
						}
					} catch (ImportacionCanceledException ie) {
						logger.error(ie.getMessage());
						break;
					}catch (Exception e) {
						e.printStackTrace();
					}
					
				}
				return null;
			}			
		});
	}
	
	protected Cliente procesar(ResultSet rs) throws SQLException{
		return (Cliente)clienteMapper.mapRow(rs,rs.getRow());
	}
	
	protected Cliente importarClienteNuevo(Cliente source){		
		return getClienteManager().save(source);
		
	}
	
	protected Cliente actualizarCliente(Cliente target,Cliente source){
		logger.info("Actualizando cliente existente: "+target);
		BeanUtils.copyProperties(source, target, new String[]{"id","version","clave"});
		ClienteCredito c=source.getCredito();
		if(c!=null){
			target.setCredito(c);
			c.setCliente(target);
			
		}
		ServiceLocator2.getHibernateTemplate().saveOrUpdate(target);
		return target;
	}
	
	
	public JdbcTemplate getSourceTemplate(){
		return ServiceLocator2.getAnalisisJdbcTemplate();
	}
	
	public ClienteManager getClienteManager(){
		return ServiceLocator2.getClienteManager();
	}
	
	private static ImportadorDeClientes INSTANCE;
	
	public static ImportadorDeClientes getInstance(){
		if(INSTANCE==null)
			INSTANCE=new ImportadorDeClientes();
		return INSTANCE;
	}

	public static void main(String[] args) {
		DBUtils.whereWeAre();
		ImportadorDeClientes imp=new ImportadorDeClientes();
		imp.importar("I110080");
	}

}
